﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboSdk;

namespace MyDeeWeibo
{
    public partial class DeeTimeline : PhoneApplicationPage
    {
        #region DependencyProperties

        #region FriendTimelineListProperty
        public static readonly DependencyProperty FriendTimelineListProperty =
            DependencyProperty.Register(
            "FriendTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> FriendTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(FriendTimelineListProperty); }
            set { SetValue(FriendTimelineListProperty, value); }
        }
        #endregion

        #region MentionTimelineListProperty
        public static readonly DependencyProperty MentionTimelineListProperty =
            DependencyProperty.Register(
            "MentionTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> MentionTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(MentionTimelineListProperty); }
            set { SetValue(MentionTimelineListProperty, value); }
        }
        #endregion

        #region CommentMentionTimelineListProperty
        public static readonly DependencyProperty CommentMentionTimelineListProperty =
            DependencyProperty.Register(
            "CommentMentionTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> CommentMentionTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(CommentMentionTimelineListProperty); }
            set { SetValue(CommentMentionTimelineListProperty, value); }
        }
        #endregion

        #region CommentsToMeProperty
        public static readonly DependencyProperty CommentsToMeProperty =
            DependencyProperty.Register(
            "CommentsToMe",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> CommentsToMe
        {
            get { return (ObservableCollection<WStatus>)GetValue(CommentsToMeProperty); }
            set { SetValue(CommentsToMeProperty, value); }
        }
        #endregion

        #region CommentsByMeProperty
        public static readonly DependencyProperty CommentsByMeProperty =
            DependencyProperty.Register(
            "CommentsByMe",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> CommentsByMe
        {
            get { return (ObservableCollection<WStatus>)GetValue(CommentsByMeProperty); }
            set { SetValue(CommentsByMeProperty, value); }
        }
        #endregion

        #region FavoritesProperty
        public static readonly DependencyProperty FavoritesProperty =
            DependencyProperty.Register(
            "FavoritesList",
            typeof(ObservableCollection<WStatus>),
            typeof(DeeTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> FavoritesList
        {
            get { return (ObservableCollection<WStatus>)GetValue(FavoritesProperty); }
            set { SetValue(FavoritesProperty, value); }
        }
        #endregion


        #region ProgressIndicatorIsVisibleProperty
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty.Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(DeeTimeline),
            new PropertyMetadata(false));

        public bool ProgressIndicatorIsVisible
        {
            get { return (bool)GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        #endregion

        private SdkCmdBase cmdBase;
        private SdkNetEngine netEngine;
        private SdkCmdBase cmdBaseMentions;
        private SdkNetEngine netEngineMentions;
        private SdkCmdBase cmdCommentMentions;
        private SdkNetEngine netEngineCommentMentions;
        private SdkCmdBase cmdCommentsToMe;
        private SdkNetEngine netEngineCommentsToMe;
        private SdkCmdBase cmdCommentsByMe;
        private SdkNetEngine netEngineCommentsByMe;
        private SdkCmdBase cmdFavorites;
        private SdkNetEngine netEngineFavorites;

        public WStatus sStatusShow; //传递页面数据

        public DeeTimeline()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {      
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.Text = "数据传输中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData.Source = this;
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsVisibleProperty, bindingData);
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsIndeterminateProperty, bindingData);

            RefreshTimeline();
        }

        private void RefreshTimeline()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new SdkNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(SdkRequestType.FRIENDS_TIMELINE, cmdBase,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses ftimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatuses));
                            ftimeliststatuses = ser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            FriendTimelineList = new ObservableCollection<WStatus>(ftimeliststatuses.statuses);
                        });
                    }
                    else
                    {
                        //Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

        private void shareIconButton_Click(object sender, EventArgs e)
        {

        }

        private void refreshIconButton_Click(object sender, EventArgs e)
        {
            RefreshTimeline();
        }

        private void sendIconButton_Click(object sender, EventArgs e)
        {
            //新建一个 SdkSend 实例
            SdkShare sdkSend = new SdkShare();
            //设置OAuth2.0的access_token
            sdkSend.AccessToken = App.AccessToken;
            //sdkSend.AccessTokenSecret = App.AccessTokenSecret;
            //定义发送微博完毕的回调函数
            sdkSend.Completed = SendCompleted;

            //调用Show方法展现页面的跳转
            sdkSend.Show();
        }

        private void profileButton_Click(object sender, EventArgs e)
        {
            //RefreshTimeline();
        }

        void SendCompleted(object sender, SendCompletedEventArgs e)
        {
            if (e.IsSendSuccess)
                MessageBox.Show("发送成功");
            else
                MessageBox.Show(e.Response, e.ErrorCode.ToString(), MessageBoxButton.OK);
        }

        private void RefreshCommentsToMe()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngineCommentsToMe = new SdkNetEngine();

            // Define a new command base
            cmdCommentsToMe = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngineCommentsToMe.RequestCmd(SdkRequestType.COMMENTS_TOME, cmdCommentsToMe,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses commentsTome = null;
                        try
                        {
                            DataContractJsonSerializer ctmser = new DataContractJsonSerializer(typeof(WStatuses));
                            commentsTome = ctmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            CommentsToMe = new ObservableCollection<WStatus>(commentsTome.comments);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        //MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

        private void RefreshCommentsByMe()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngineCommentsByMe = new SdkNetEngine();

            // Define a new command base
            cmdCommentsByMe = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngineCommentsByMe.RequestCmd(SdkRequestType.COMMENTS_BYME, cmdCommentsByMe,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses commentsByme = null;
                        try
                        {
                            DataContractJsonSerializer ctmser = new DataContractJsonSerializer(typeof(WStatuses));
                            commentsByme = ctmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            CommentsByMe = new ObservableCollection<WStatus>(commentsByme.comments);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        //MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

        private void UserSettings_Click(object sender, System.EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageViews/UserSettings.xaml", UriKind.Relative));
        }

        private void Discovery_Click(object sender, System.EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageViews/UserSettings.xaml", UriKind.Relative));
        }

        private void RefreshMentionTimeline()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngineMentions = new SdkNetEngine();

            // Define a new command base
            cmdBaseMentions = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngineMentions.RequestCmd(SdkRequestType.MENTIONS_TIMELINE, cmdBaseMentions,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses mtimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer mser = new DataContractJsonSerializer(typeof(WStatuses));
                            mtimeliststatuses = mser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            MentionTimelineList = new ObservableCollection<WStatus>(mtimeliststatuses.statuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        //MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

        private void RefreshCommentMentions()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngineCommentMentions = new SdkNetEngine();

            // Define a new command base
            cmdCommentMentions = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngineCommentMentions.RequestCmd(SdkRequestType.COMMENT_MENTIONS, cmdCommentMentions,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses cmtimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer cmser = new DataContractJsonSerializer(typeof(WStatuses));
                            cmtimeliststatuses = cmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            CommentMentionTimelineList = new ObservableCollection<WStatus>(cmtimeliststatuses.comments);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        //MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

        private void MainPivot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            RefreshFavorites();
        }

        private void MainPivot_LoadingPivotItem(object sender, PivotItemEventArgs e)
        {
            
        }

        private void weiboButton_Click(object sender, RoutedEventArgs e)
        {
            RefreshMentionTimeline();
            mentionsTimeline.Visibility = Visibility.Visible;
            commentmentionsTimeline.Visibility = Visibility.Collapsed;
        }

        private void commentButton_Click(object sender, RoutedEventArgs e)
        {
            RefreshCommentMentions();
            commentmentionsTimeline.Visibility = Visibility.Visible;
            mentionsTimeline.Visibility = Visibility.Collapsed;
        }

        private void friendsTimeline_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
            //MessageBox.Show(sID);
        }

        //页面数据传递
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            MainPage loginInstance = e.Content as MainPage;
            WeiboContent StatusShow = e.Content as WeiboContent;
            if (StatusShow != null)
            {
                StatusShow.StatusResults = sStatusShow;
            }
        }

        private void toMe_Click(object sender, RoutedEventArgs e)
        {
            RefreshCommentsToMe();
            commentsToMe.Visibility = Visibility.Visible;
            commentsByMe.Visibility = Visibility.Collapsed;
        }

        private void byMe_Click(object sender, RoutedEventArgs e)
        {
            RefreshCommentsByMe();
            commentsByMe.Visibility = Visibility.Visible;
            commentsToMe.Visibility = Visibility.Collapsed;
        }

        private void RefreshFavorites()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngineFavorites = new SdkNetEngine();

            // Define a new command base
            cmdFavorites = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "20"
            };


            // Request server, the last parameter is set as default (".json")
            netEngineFavorites.RequestCmd(SdkRequestType.FAVORITES, cmdFavorites,
                // Requeset callback
                delegate(SdkRequestType requestType, SdkResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == SdkErrCode.SUCCESS)
                    {
                        WStatuses favliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer cmser = new DataContractJsonSerializer(typeof(WStatuses));
                            favliststatuses = cmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            FavoritesList = new ObservableCollection<WStatus>(favliststatuses.favorites);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                        //MessageBox.Show("未授权，请再次点击【登录/授权】按钮进行应用授权！");
                        //Debug.WriteLine(response.content, response.errCode.ToString());
                    }
                });
        }

    }
}
